package rfp1;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.junit.After;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class r2 { 

	WebDriver driver;
	String URL;
	String vzip;
	String vMin;
	String vMax;
	String vbeds;
	String vbaths;
	String Appzip, zipresult, Appmin, minresult, Appmax, maxresult, Appbeds, x ,Temp, bedsresult, Appbaths, bathsresult;
	String vTemp, vAppSearchResult, vSearchResult,SearchRes ,vResult;
	String vError;
	int xRows, xCols;	
	String[][] vTD;
	
	@Test
	public void Attest() throws Exception{	
			
	/*	URL="http://www.redfin.com/";
	    vzip = "91367";
		vMin ="$100,000";
		vMax ="$400,000";
		vbeds= "3 +";
		vbaths= "No min";
		vSearchResult = "2 results";*/
		
		vTD = readXL("C:\\Users\\Karthikeyan\\Desktop\\RedfinRemake.xls","TestData");
		for(int p=1;p<vTD.length;p++){
			if(vTD[p][12].equals("Y")){
				try{
					vError ="";
					URL=vTD[p][2];
					vzip =vTD[p][3];
					vMin =vTD[p][4];
					vMax= vTD[p][5];
					vbeds =vTD[p][6];
					vbaths = vTD[p][7];
					vSearchResult =vTD[p][8];
					driver = new FirefoxDriver();
					driver.navigate().to(URL);
					driver.findElement(By.xpath("//input[@class='dijitReset dijitInputInner']")).sendKeys(vzip);
					//driver.findElement(By.xpath("//select[@title='Minimum price']")).sendKeys(arg0);
					Select mys= new Select(driver.findElement(By.xpath("//select[@title='Minimum price']")));
					mys.selectByVisibleText(vMin);
					mys= new Select(driver.findElement(By.xpath("//select[@title='Maximum price']")));
					mys.selectByVisibleText(vMax);
					mys = new Select(driver.findElement(By.xpath("//select[@name='num_beds']")));
					mys.selectByVisibleText(vbeds);
					mys = new Select(driver.findElement(By.xpath("//select[@name='num_baths']")));
					mys.selectByVisibleText(vbaths);
					driver.findElement(By.xpath("//input[@type ='submit']")).click();
					Thread.sleep(10000);
					
					//TC001 Comparing the Expected and Actual results of Zip
					Appzip= driver.findElement(By.xpath("//input[@id='search_location']")).getAttribute("value");
					System.out.println("Expected zip code is " +vzip);
					System.out.println("Actual zip code is " +Appzip);
							
					if (Appzip.equals(vzip)){
						zipresult = "Pass";
						System.out.println("Pass");
					}else{
						zipresult = "Fail";
						System.out.println("Fail");
						vError = "Step1: Zip values were not equal";
						
					}
					print();
				
					//TC002 Comparing the Expected and Actual results of Min price
					Appmin= driver.findElement(By.xpath("//select[@id='min_price']")).getAttribute("value");
					x="";
					Temp= vMin.substring(1);
					String[] A= Temp.split(",");
					for(int i=0;i<A.length;i++){
						x=x+A[i];
					} 
					System.out.println("Expected min value is " +x);
					System.out.println("Actual min value is "+ Appmin);
							
					if (Appmin.equals(x)){
						minresult="Pass";
						System.out.println("Pass");	
					}else{
						minresult= "Fail";
						System.out.println("fail");
						vError = vError + " Step 2: Min Prices  values were not equal";
					}
					print();
					
					
					//TC003 Comparing the expected and actual results of Max price
					Appmax = driver.findElement(By.xpath("//select[@id='max_price']")).getAttribute("value");
					x="";
					Temp= vMax.substring(1);
					String[] B= Temp.split(",");
					for(int i=0;i<B.length;i++){
						x=x+B[i];
					}
					System.out.println("Expected max value is " +x);
					System.out.println("Actual max value is "+ Appmax);
							
					if (Appmax.equals(x)){
						maxresult="Pass";   // so the test case is pass
						System.out.println("Pass");	// for the display in console
					}else{
						maxresult= "Fail";
						System.out.println("fail");
						vError = vError + " Step 3: Max Prices  values were not equal";
					}
					print();
						
					//TC004 comparing Expected and Actual Results of beds
					Appbeds= driver.findElement(By.xpath("//select[@id='num_beds']")).getAttribute("value");
					Temp="";
					Temp=vbeds.substring(0,1);
					System.out.println("expected beds value is " +Temp);
					System.out.println("Actual beds value is " +Appbeds);
					   
					if(Appbeds.equals(Temp)){
						bedsresult="Pass";
						System.out.println("Pass");
					}else{
						bedsresult="Fail";
						System.out.println("Fail");
						vError = vError + " Step 4: Beds values were not equal";
					}
					print();
			
					
					//TC005 comparing Expected and Actual Results of Baths
					driver.findElement(By.xpath("//span[@id='more_options']")).click();
					Appbaths= driver.findElement(By.xpath("//select[@id='num_baths']")).getAttribute("value");
					vTemp = "";
					System.out.println("expected baths value is " +vTemp);
					System.out.println("Actual baths value is " +Appbaths);
					if(Appbaths.equals(vTemp)){
						bathsresult="Pass";
						System.out.println("Pass");
					}else{
						bathsresult="Fail";
						System.out.println("Fail");
						vError = vError + " Step 5: Baths values were not equal";
					}
					print();
					
					//TC006
					vAppSearchResult=driver.findElement(By.xpath("//span[@dojoattachpoint='numResultsNode']")).getText();
					System.out.println("Expected Search results is " +vSearchResult);
					System.out.println("Actual Search results is " +vAppSearchResult);
					if(vAppSearchResult.equals(vSearchResult)){
						SearchRes="Pass";
						System.out.println("Pass");
					}else{
						SearchRes="Fail";
						System.out.println("Fail");
						vError = vError + " Step 6: Search Results were not equal";
					}
					print();
					
					//Comparing Overall Test Case Results
					if(zipresult.equals("Pass") && minresult.equals("Pass") && maxresult.equals("Pass") && bedsresult.equals("Pass") && bathsresult.equals("Pass") && SearchRes.equals("Pass")){
						 vResult ="Pass";
						 vTD[p][9] ="Pass";
						 vTD[p][10] ="--";
						 vTD[p][11] ="--";
						 System.out.println("Overall Test Case is PASS");
					}else{
						vResult ="Fail";
						 vTD[p][9] ="Fail";
						 vTD[p][10] = vError;
						 File scr = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
						 FileUtils.copyFile(scr,new File("C:\\Users\\Karthikeyan\\Desktop\\Screenshots\\Error-"+vTD[p][1]+".png"));
						 vTD[p][11] = "C:\\Users\\Karthikeyan\\Desktop\\Screenshots\\Error-"+vTD[p][1]+".png"; 
						 System.out.println("Overall Test Case is FAIL");                                                                                                                                                                                           
					}
					
					print();
					driver.quit();
				}catch(Exception e){
					System.out.println("Due to error " + e);
					vTD[p][9] = "Error";
					vTD[p][10] = "Due to error:" + e;
					vTD[p][11] = "Error";
				}
			}else{
				vTD[p][9] = "Skipped";
				vTD[p][10] = "Skipped";
				vTD[p][11] = "Skipped";
			}
		}
	}
	
	@After
	public void AtAfter() throws Exception{
		writeXL("C:\\Users\\Karthikeyan\\Desktop\\RedfinResult.xls","TestResults", vTD);
	}
	
	
	
	public void print(){
		System.out.println("----------------------------------------------------------------");
		System.out.println("----------------------------------------------------------------");	
	}
	
	//Read XL
	
	public String[][] readXL(String spath, String isheet) throws Exception {
		
		File myXL = new File (spath);
		FileInputStream myStream = new FileInputStream(myXL);
		HSSFWorkbook myWB = new HSSFWorkbook(myStream);
		HSSFSheet mySheet = myWB.getSheet(isheet);
		xRows = mySheet.getLastRowNum()+1;
		xCols = mySheet.getRow(0).getLastCellNum();
		String[][] xData = new String[xRows][xCols];
		for(int i=0;i< xRows;i++){
			HSSFRow row = mySheet.getRow(i);
			for(int j=0;j<xCols;j++){
				HSSFCell cell = row.getCell(j);
				String value = cellToString(cell);
				xData[i][j] = value;
				
			}
		}
		
		return xData;
	}
		
		// Method to write into an XL
		public void writeXL(String sPath, String iSheet, String[][] xData) throws Exception{

	    	File outFile = new File(sPath);
	        HSSFWorkbook wb = new HSSFWorkbook();
	        HSSFSheet osheet = wb.createSheet(iSheet);
	        int xR_TS = xData.length;
	        int xC_TS = xData[0].length;
	    	for (int myrow = 0; myrow < xR_TS; myrow++) {
		        HSSFRow row = osheet.createRow(myrow);
		        for (int mycol = 0; mycol < xC_TS; mycol++) {
		        	HSSFCell cell = row.createCell(mycol);
		        	cell.setCellType(HSSFCell.CELL_TYPE_STRING);
		        	cell.setCellValue(xData[myrow][mycol]);
		        }
		        FileOutputStream fOut = new FileOutputStream(outFile);
		        wb.write(fOut);
		        fOut.flush();
		        fOut.close();
	    	}
			}

		//Change cell type
		public static String cellToString(HSSFCell cell) { 
			// This function will convert an object of type excel cell to a string value
			int type = cell.getCellType();                        
			Object result;                        
			switch (type) {                            
				case HSSFCell.CELL_TYPE_NUMERIC: //0                                
					result = cell.getNumericCellValue();                                
					break;                            
				case HSSFCell.CELL_TYPE_STRING: //1                                
					result = cell.getStringCellValue();                                
					break;                            
				case HSSFCell.CELL_TYPE_FORMULA: //2                                
					throw new RuntimeException("We can't evaluate formulas in Java");  
				case HSSFCell.CELL_TYPE_BLANK: //3                                
					result = "";                                
					break;                            
				case HSSFCell.CELL_TYPE_BOOLEAN: //4     
					result = cell.getBooleanCellValue();       
					break;                            
				case HSSFCell.CELL_TYPE_ERROR: //5       
					throw new RuntimeException ("This cell has an error");    
				default:                  
					throw new RuntimeException("We don't support this cell type: " + type); 
					}                        
			return result.toString();      
			}
		
		
	
	
	
}
